package com.cloudbroker.bcs.platform.ltb.common.extservice.store.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.cloudbroker.bcs.common.util.DateTimeUtil;
import com.cloudbroker.bcs.common.util.IOUtil;
import com.cloudbroker.bcs.platform.ltb.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.ltb.common.extservice.store.StoreFields;
import com.cloudbroker.bcs.platform.ltb.common.extservice.store.StoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service(StoreFields.IMPL_TYPE_OSS)
public class AliyunOSSStoreServiceImpl implements StoreService {
	private static Logger logger = LoggerFactory.getLogger(AliyunOSSStoreServiceImpl.class);
	private OSSClient client;
	private String INNER_DOMAIN;
	private String BUCKET_NAME;
	private String ACCESS_ID;
	private String ACCESS_KEY;
	private String DEBUG;

	public static void main(String[] args) {
		OSSClient client = new OSSClient("bAXZXKLoFHFF2C4n", "9Vlwib5n2T2xGPPXUuauDaWxFSjMQa");
		ObjectListing list = client.listObjects("ifsdav" , "93_");
		for(OSSObjectSummary summary : list.getObjectSummaries()) {
			System.out.println(DateTimeUtil.toString(summary.getLastModified()) );
		}
	}
	
	@SuppressWarnings("deprecation")
	public void initialize(Map<String, Object> params) {
		INNER_DOMAIN = ConfigValues.getOSSInnerDomain();
		ACCESS_ID = ConfigValues.getOSSAccessId();
		ACCESS_KEY = ConfigValues.getOSSAccessKey();
		BUCKET_NAME = ConfigValues.getOSSBucketName();
		DEBUG       = ConfigValues.getOSSDebug();

		logger.info("OSS INNER DOMAIN : " + INNER_DOMAIN);
		logger.info("ACCESS_KEY:"+ACCESS_ID);
		logger.info("ACCESS_SECRET:"+ACCESS_KEY);
		logger.info("BUCKET_NAME:"+BUCKET_NAME);

		if ("true".equals(DEBUG)) {
			client = new OSSClient(ACCESS_ID, ACCESS_KEY);
		}
		else {
			client = new OSSClient(INNER_DOMAIN, ACCESS_ID, ACCESS_KEY);
		}
		if (!client.doesBucketExist(BUCKET_NAME)){
			client.createBucket(BUCKET_NAME);
		}
	}

	public String uploadFile(String key, String filename) throws Exception {
        File file = new File(filename);
        return uploadFile(key, file);
    }
    
    public String uploadFile(String key, byte[] data) throws Exception {
        return uploadFile(key, new ByteArrayInputStream(data), data.length, true);
    }
    
    public String uploadFile(String key, File file) throws Exception {
        return uploadFile(key, new FileInputStream(file), file.length(), true);
    }
    
    public String uploadFile(String key, InputStream in,long length) throws Exception {
    	try{
    		ObjectMetadata objectMeta = new ObjectMetadata();
            objectMeta.setContentLength(length);
            client.putObject(BUCKET_NAME, key, in, objectMeta);
            return key;
    	}finally{
			IOUtil.close(in);
    	}
    }
    public String uploadFile(String key, InputStream in, long contentLength, boolean closeIn) throws Exception {
    	try{
    		ObjectMetadata objectMeta = new ObjectMetadata();
            objectMeta.setContentLength(contentLength);
            client.putObject(BUCKET_NAME, key, in, objectMeta);
            return key;
    	}finally{
    		if (closeIn) {
    			IOUtil.close(in);
    		}
    	}
    }
    
    @SuppressWarnings("unused")
	public InputStream downloadFile(String key) {
        OSSObject ossObject = client.getObject(BUCKET_NAME, key);
        if(null != ossObject){
        	ObjectMetadata objectMeta = ossObject.getObjectMetadata();
        	return ossObject.getObjectContent();
        }
        return null;
    }
    
    public boolean downloadFile(String key, File file) {
        InputStream in = downloadFile(key);
        return IOUtil.streamToFile(in, file, true);
    }
    
    public List<String> listObjectKey() {
        List<String> keys = new ArrayList<String>();
        ObjectListing obList = client.listObjects(BUCKET_NAME);
        List<OSSObjectSummary> summaries = obList.getObjectSummaries();
        for (OSSObjectSummary summary : summaries) {
            keys.add(summary.getKey());
        }
        return keys;
    }

    public boolean deleteObject(String key) throws Exception {
        client.deleteObject(BUCKET_NAME, key);
        return true;
    }
    
	public String getObjectETag(String key) {
		OSSObject ossObject = client.getObject(BUCKET_NAME, key);
		ObjectMetadata objectMeta = ossObject.getObjectMetadata();
		return objectMeta.getETag();
	}



	public void destory() {
		client.shutdown();
	}

	@Override
	public String uploadFile(String key, InputStream ips) throws Exception {
		return uploadFile(key , IOUtil.streamToBytes(ips) );
	}
	

}
